#import "MRLabel.h"

/*===================================================================
 自定标签
 ==================================================================*/
@implementation MRLabel

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self awakeFromNib];
    }
    return self;
}

- (void)awakeFromNib
{
	[super awakeFromNib];
	
    if (_space == 0) _space = 4;
	if (_scale == 0) _scale = 1;
}

- (void)dealloc
{
	[_tmrInfo invalidate];
	_texts = nil;
}

- (void)layoutSubviews
{
	[super awakeFromNib];
	[super layoutSubviews];
}

#pragma mark - 属性
- (void)setAutoWidth:(NSInteger)autoWidth
{
	_autoWidth = autoWidth;
	
	//获取自动布局对象
	for (NSLayoutConstraint *c in self.constraints)
	{
		if (c.firstItem == self && c.firstAttribute == NSLayoutAttributeWidth && c.secondItem == nil)
			_width = c;
		else if (c.firstItem == self && c.firstAttribute == NSLayoutAttributeLeft)
			_left = c;
		else if (c.firstItem == self && c.firstAttribute == NSLayoutAttributeRight)
			_right = c;
	}
	
	[self setText:self.text];
	[self setNeedsDisplay];
}

- (void)setFont:(UIFont *)font
{
	[super setFont:font];
	if (_autoWidth) [self setText:self.text];
}

- (void)setString:(NSString *)string
{
	_string = string;
	if (_autoWidth) [self setText:self.text];
}

- (void)setImage:(UIImage *)image
{
	_image = image;
	if (_autoWidth) [self setText:self.text];
	[self setNeedsDisplay];
}

- (void)setHead:(UIImage *)head
{
	_head = head;
	if (_autoWidth) [self setText:self.text];
	[self setNeedsDisplay];
}

- (void)setSpace:(CGFloat)space
{
	_space = space;
	if (_autoWidth) [self setText:self.text];
	[self setNeedsDisplay];
}

- (void)setScale:(CGFloat)scale
{
	_scale = scale;
	if (_autoWidth) [self setText:self.text];
	[self setNeedsDisplay];
}

- (void)setNeedsLayout
{
	[super setNeedsLayout];
	if (_autoWidth) [self setText:self.text];
	[self setNeedsDisplay];
}

/*===================================================================
 说明:
	带格式的文本
	xxx{x1:1,x2:'12'}
 ==================================================================*/
- (void)setFormatText:(NSString *)formatText
{
	_formatText = formatText;
	NSRange range = [_formatText rangeOfString:@"\\{.*\\}$" options:NSRegularExpressionSearch];
	
	if (range.length)
	{
		NSString *sub = [_formatText substringWithRange:range];
		NSDictionary *dict = [NSDictionary dictionaryWithString:[sub stringByReplacingOccurrencesOfString:@"'" withString:@"\""]];
		
		if (dict == nil)
		{
			_string = [sub substringWithRange:NSMakeRange(1, sub.length-2)];
		}
		
		[self setText:[_formatText substringToIndex:range.location]];
	}
	else
	{
		_string = nil;
		[self setText:formatText];
	}
}

/*===================================================================
 说明:
    重置自动宽度
 ==================================================================*/
- (void)setText:(NSString *)text
{
	if (_keepZero > MRLabelKeepZeroFree)      //去除后缀零(数字)
	{
		int c = 0;
		NSRange range = [text rangeOfString:@"."];
		
		NSUInteger i = text.length - 1;
		for (; i>=(range.location + _keepZero); i--)
		{
			if ([[text substringWithRange:NSMakeRange(i,1)] isEqualToString:@"0"]) c ++; else break;
		}
		
		if (c && range.length)
		{
			if ([[text substringWithRange:NSMakeRange(i,1)] isEqualToString:@"."]) c ++;
			text = [text substringToIndex:text.length - c];
		}
	}
	
    if (_autoWidth)     //自动宽度
    {
		CGFloat fh  = self.font.pointSize * .94;
		CGFloat width = _contentInset.left + _contentInset.right;
		
		if (text.length)
		{
			width += [text sizeWithAttributes:@{NSFontAttributeName:self.font}].width;
		}
		
		//计算图像或文字大小
		if (_head)
		{
			CGFloat zoom = _head.size.height ? _head.size.width / _head.size.height : 0;
			width += LOCPIXEL(fh * zoom * _scale) + (text.length && zoom ? _space : 0);
		}
		
		if (_image)
		{
			CGFloat zoom = _image.size.height ? _image.size.width / _image.size.height : 0;
			width += LOCPIXEL(fh * zoom * _scale) + (text.length && zoom ? _space : 0);
		}
		else if (_string)
		{
			UIFont *font = _stringFont ? _stringFont : [self.font fontWithSize:LOCPIXEL(self.font.pointSize * _scale * .6)];
			width += [_string sizeWithAttributes:@{NSFontAttributeName:font}].width + (text.length ? _space : 0);
		}
		
		if (_autoWidth > 0)
			width = ceil(width / _autoWidth) * _autoWidth;
		else if (width < ABS(_autoWidth))
			width = ABS(_autoWidth);
		
        //重置宽度
        if (_width)    //自动布局
        {
            _width.constant = LOCPIXEL(width + .5);
			[self layoutIfNeeded];
        }
        else if (self.textAlignment == NSTextAlignmentRight || (self.textAlignment == NSTextAlignmentCenter && _autoWidth > 0))
        {
            self.frame = CGRectMake(self.frame.origin.x + self.frame.size.width - width, self.frame.origin.y, width, self.frame.size.height);
        }
		else if (self.textAlignment != NSTextAlignmentCenter || (self.textAlignment == NSTextAlignmentCenter && _autoWidth < 0))
        {
            self.frame = (CGRect){self.frame.origin, CGSizeMake(width, self.frame.size.height)};
        }
    }
    
    [super setText:text];
}

#pragma mark - 绘制
/*===================================================================
 说明:
	根据边界调区域
 ==================================================================*/
static CGRect edgeInsetsInsetRect(CGRect rect, UIEdgeInsets insets)
{
	if (insets.left && insets.left < 1.f)		insets.left   = LOCPIXEL(rect.size.width * insets.left);
	if (insets.right && insets.right < 1.f)		insets.right  = LOCPIXEL(rect.size.width * insets.right);
	if (insets.top && insets.top < 1.f)			insets.top    = LOCPIXEL(rect.size.height * insets.top);
	if (insets.bottom && insets.bottom < 1.f)	insets.bottom = LOCPIXEL(rect.size.height * insets.bottom);
	
	return UIEdgeInsetsInsetRect(rect, insets);
}

/*===================================================================
 说明:
    重绘
 ==================================================================*/
- (void)drawTextInRect:(CGRect)rect
{
	UIFont *font = _stringFont ? _stringFont : [self.font fontWithSize:LOCPIXEL(self.font.pointSize * _scale * .6)];
	rect = edgeInsetsInsetRect(rect, _contentInset);
    
    CGRect rcHead = CGRectZero;
	CGRect rcTail = CGRectZero;
	
	CGRect rc = rect;
	//rc.origin.x += 2;
	
	CGSize size = self.text.length ? [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}] : CGSizeZero;
	CGFloat fh  = self.font.pointSize * .9;
	
    //计算图像或文字大小
	if (_head)
	{
		CGFloat zoom = (_head.size.height ? _head.size.width / _head.size.height : 0);
		rcHead.size = CGSizeMake(LOCPIXEL(fh * zoom * _scale), LOCPIXEL(fh * _scale));
		rcHead.origin.y = (rect.size.height - rcHead.size.height) / 2 + rect.origin.y;
	}
	
    if (_image)
    {
		CGFloat zoom = _image.size.height ? _image.size.width / _image.size.height : 0;
        rcTail.size = CGSizeMake(LOCPIXEL(fh * zoom * _scale), LOCPIXEL(fh * _scale));
		rcTail.origin.y = (rect.size.height - rcTail.size.height) / 2 + rect.origin.y;
    }
    else if (_string)
    {
		rcTail.size = [_string sizeWithAttributes:@{NSFontAttributeName:font}];
        rcTail.origin.y = self.font.ascender - rcTail.size.height + (rect.size.height - size.height - font.descender) / 2 + rect.origin.y;
    }
    
    //重新分配原文字区域
    if (_head || _image || _string)
    {
		CGFloat w1 = _head && rcHead.size.width ? rcHead.size.width + _space : 0;
		CGFloat w2 = (_image || _string) ? (rcTail.size.width ? rcTail.size.width + _space : 0) : 0;
		
        if ((size.width + w1 + w2) > rect.size.width)			//合并后大于原始区域时
        {
			rc.origin.x += w1;
            rc.size.width -= w1 + w2;
			
            rcTail.origin.x = rect.origin.x + rect.size.width - rcTail.size.width;
        }
        else if (self.textAlignment == NSTextAlignmentCenter)   //居中对齐
        {
			rcHead.origin.x = rc.origin.x + (rect.size.width - size.width - w1 - w2) / 2;
			
			rc.origin.x = rcHead.origin.x + w1;
            rc.size.width = size.width;
			
			rcTail.origin.x = rc.origin.x + rc.size.width + _space;
        }
        else if (self.textAlignment == NSTextAlignmentRight)    //右对齐
        {
			rc.origin.x += rect.size.width - w2 - size.width;
            rc.size.width = size.width;
            
            rcHead.origin.x = rc.origin.x - w1;
			rcTail.origin.x = rect.origin.x + rect.size.width - rcTail.size.width;
        }
		else		//左对齐或其它对齐
		{
			rc.origin.x += w1;
            rc.size.width = size.width;
			
            rcTail.origin.x = rc.origin.x + size.width + _space;
		}
    }
	
    //绘制内容
	[super drawTextInRect:rc];
	
	if (_head) [_head drawInRect:rcHead];
	
    if (_image)
    {
        [_image drawInRect:rcTail];
    }
    else if (_string)
    {
		UIColor *clr = _stringColor ? _stringColor : [self.textColor colorWithAlphaComponent:.6];
		[_string drawInRect:rcTail withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:clr}];
    }
}

#pragma mark - 特效
/*===================================================================
 说明:
	动态翻滚文本
 ==================================================================*/
- (void)setTexts:(NSArray<NSDictionary *> *)texts
{
	_texts = texts;
	[_tmrInfo invalidate];
	_idxInfo = 0;
	[self setInfoAttributes];
	
	if (_texts.count > 1)
	{
		_tmrInfo = [NSTimer timerWithTimeInterval:2.5 target:self selector:@selector(showInfoAttributes) userInfo:nil repeats:YES];
		[[NSRunLoop mainRunLoop] addTimer:_tmrInfo forMode:NSRunLoopCommonModes];
	}
	else
	{
		[self.layer removeAllAnimations];
	}
}

- (void)setInfoAttributes
{
	NSDictionary *d = _texts[_idxInfo];
	
	if (d[INFOFONT]) self.font = d[INFOFONT];
	if (d[INFOCOLOR]) self.textColor = d[INFOCOLOR];
	if (d[INFOIMAGE]) self.head = d[INFOIMAGE];
	if (d[INFOTEXT]) self.text = d[INFOTEXT];
}

- (void)showInfoAttributes
{
	if (++_idxInfo == _texts.count) _idxInfo = 0;
	[self setInfoAttributes];
	
	CATransition *animation = [CATransition animation];
	animation.duration = 0.7;
	animation.type = @"oglFlip";
	[self.layer addAnimation:animation forKey:nil];
}

@end
